<?php

namespace App\Imports;

use App\Http\Models\Base\PayerCategory;
use App\Http\Models\Business\Payer;
use Exception;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class PayerImport implements ToCollection, WithHeadingRow
{
    use BaseImportTrait;

    private $required_field = ['客户代码', '客户名称', '客户分类代码'];

    private $payer_category_array = [];

    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function collection(Collection $rows)
    {

        foreach ($rows as $key => $row) {
            $row = $row->toArray();

            if ($key === 0) {
                $this->verifyField($row);
                $this->prepareBaseData();
            }

            $this->verifyNotNull($row, $key + 2);
            $this->verifyValueExist($row, $key + 2);

            $this->saveData($row);
        }
    }

    //准备基础数据，用来验证
    private function prepareBaseData()
    {
        $this->payer_category_array = PayerCategory::pluck('code')->toArray();
    }

    //验证字段值存在于数据库基础表中
    private function verifyValueExist(array $row, int $index)
    {
        if (!in_array($row['客户分类代码'], $this->payer_category_array)) {
            $this->no_error = false;
            $this->error_field = '客户分类代码';
        }

        if (!$this->no_error) {
            throw new Exception('第 ' . $index . ' 行中的 [' . $this->error_field . '] 的值不存在于系统中！');
        }
    }

    //保存数据
    private function saveData(array $row)
    {
        Payer::updateOrCreate(
            ['code' => $row['客户代码']],
            ['name' => $row['客户名称'], 'category_code' => $row['客户分类代码']]
        );
    }
}
